package com.yklx.youke.admin.controller;

import com.yklx.youke.admin.service.UserRoleService;
import com.yklx.youke.entity.UserRole;
import com.yklx.youke.util.ApiResponse;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/admin/user-roles")
@PreAuthorize("hasAuthority('user-role:read') or hasAuthority('user-role:write')")
public class UserRoleController {

    private final UserRoleService userRoleService;

    public UserRoleController(UserRoleService userRoleService) {
        this.userRoleService = userRoleService;
    }

    @GetMapping("/user/{userId}")
    public ResponseEntity<ApiResponse<List<UserRole>>> getUserRoles(@PathVariable String userId) {
        List<UserRole> userRoles = userRoleService.getUserRolesByUserId(userId);
        return ResponseEntity.ok(ApiResponse.success(userRoles));
    }

    @PreAuthorize("hasAuthority('user-role:write')")
    @PostMapping
    public ResponseEntity<ApiResponse<Boolean>> assignRoleToUser(@RequestParam String userId, @RequestParam String roleId) {
        boolean success = userRoleService.assignRoleToUser(userId, roleId);
        if (success) {
            return ResponseEntity.ok(ApiResponse.success("角色分配成功", true));
        } else {
            return ResponseEntity.ok(ApiResponse.error("角色分配失败"));
        }
    }

    @PreAuthorize("hasAuthority('user-role:write')")
    @DeleteMapping
    public ResponseEntity<ApiResponse<Boolean>> removeRoleFromUser(@RequestParam String userId, @RequestParam String roleId) {
        boolean success = userRoleService.removeRoleFromUser(userId, roleId);
        if (success) {
            return ResponseEntity.ok(ApiResponse.success("角色移除成功", true));
        } else {
            return ResponseEntity.ok(ApiResponse.error("角色移除失败"));
        }
    }

    @PreAuthorize("hasAuthority('user-role:write')")
    @DeleteMapping("/user/{userId}")
    public ResponseEntity<ApiResponse<Boolean>> removeAllRolesFromUser(@PathVariable String userId) {
        boolean success = userRoleService.removeAllRolesFromUser(userId);
        if (success) {
            return ResponseEntity.ok(ApiResponse.success("用户所有角色已移除", true));
        } else {
            return ResponseEntity.ok(ApiResponse.error("移除用户角色失败"));
        }
    }
}